package com.shujiaotong.controller;


import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shujiaotong.common.R;
import com.shujiaotong.pojo.Admin;
import com.shujiaotong.pojo.Room;
import com.shujiaotong.service.IRoomService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2024-10-20
 */
@RestController
@RequestMapping("/room")
@Slf4j
public class RoomController {

    @Autowired
    private IRoomService roomService;

//    分页
    @GetMapping("page")
    public R page(
            @RequestParam int page,
            @RequestParam int pageSize,
            @RequestParam(required = false) String name){
    //        接收参数
        log.info("当前页:{},页条数:{},教室:{}",page,pageSize,name);
    //        分页条件
        Page<Room> roomPage = new Page<>(page,pageSize);
    //        查询条件
        LambdaQueryWrapper<Room> qw = new LambdaQueryWrapper<>();
        qw.like(!StringUtils.isEmpty(name),Room::getName,name);

    //        分页查询
        roomService.page(roomPage,qw);
    //        返回值
        return R.success(roomPage);

    }
//新增教室
    @PostMapping
    public R save(@RequestBody Room room){
        log.info("新增教室:{}",room);

        room.setStatus(1);// 正常
        room.setPeople(100);
        boolean save = roomService.save(room);


        return save?R.success("新增成功"):R.error("新增失败");
    }

//    删除教室,kv传参
    @DeleteMapping
    public R delete(Long id){
        log.info("删除教室:{}",id);
        boolean removeById = roomService.removeById(id);
        return removeById?R.success("删除成功"):R.error("删除失败");
    }

//    根据id查询教室

    @GetMapping("/{id}")
    public R getById(@PathVariable Long id ){
        log.info("根据id查询教室:{}",id);
        Room room = roomService.getById(id);
        return R.success(room);
    }

//修改教室
    @PutMapping
    public R update(@RequestBody Room room){
        log.info("修改教室:{}",room);
        boolean update = roomService.updateById(room);
        return update?R.success("修改成功"):R.error("修改失败");
    }

//    修改教室状态
    @PutMapping("changeStatus")
    public R changeStatus(@RequestBody Room room){
            Room room1 = roomService.getById(room.getId());
            if (room1.getStatus()==0){
                room1.setStatus(1);
                return roomService.updateById(room1)?R.success("启用成功"):R.error("启用失败");
            }else {
                room1.setStatus(0);
                return roomService.updateById(room1)?R.success("禁用成功"):R.error("禁用失败");
            }
    }

//查询所有教室的名字，只查名字
    @GetMapping
    public R list(){
        List<String> roomNames = roomService.getRoomNames();
        return R.success(roomNames);
    }
}
